<template>
  <div>
    <el-card :class="{'cardInTab':true}" shadow="never" key="card2">

      <el-row :class="['spuBar']">
        <el-col :span="4"><b>产品SPU编号:</b> {{prodCurrentSpu.code}}</el-col>
        <el-col :span="10"><b>产品SPU名称:</b> {{prodCurrentSpu.name}}</el-col>
        <el-col :span="4"><b>品牌:</b> {{prodCurrentSpu.brandName}}</el-col>
        <el-col :span="6"><b>分类:</b> {{prodCurrentSpu.cate1Name}} > {{prodCurrentSpu.cate2Name}} >
          {{prodCurrentSpu.cate3Name}}
        </el-col>
      </el-row>


      <el-row :class="['bottomLine']" v-if="prodCurrentSpu.attrs">
        <el-col :span="2"><h1>属性参数列表:</h1></el-col>
        <el-col :span="4" v-if="prodCurrentSpu.attrs.length==0"><h4>所属分类没有属性参数</h4></el-col>
        <el-col :span="22" v-else :class="['attrListContext']">
          <el-tag :class="['attrListTag']" v-for="attr of prodCurrentSpu.attrs" :key="attr.id">{{attr.name}}</el-tag>
        </el-col>
      </el-row>

      <el-row :class="['bottomLine']" v-if="prodCurrentSpu.specs">
        <el-col :span="2"><h1>规格参数列表:</h1></el-col>
        <el-col :span="4" v-if="prodCurrentSpu.specs.length==0" :class="['placeholder']"><h4>所属分类没有规格参数</h4></el-col>
        <el-col :span="22" v-else :class="['attrListContext']">
          <el-tag :class="['specListTag']" v-for="spec of prodCurrentSpu.specs" :key="spec.id">{{spec.name}}</el-tag>
        </el-col>
      </el-row>

      <el-row :class="['bottomLine']" v-if="prodCurrentSpuImages">
        <el-col :span="2"><h1>图片列表:</h1></el-col>
        <el-col :span="22" :class="['attrListContext']">
          <image-list-edit :data="prodCurrentSpuImages"
                           :image-server="imageServer"
                           :item-key-name="'id'"
                           :oss-server="ossServer"
                           :item-url-name="'image'"
                           @on-remove="handleRemoveImage"
                           @on-success="handleImageListEditUploadSuccess"
          ></image-list-edit>
        </el-col>
      </el-row>




      <el-row :class="['btnBar']">
        <el-button type="primary" @click="handleRefreshSkuListButtonClick(prodCurrentSpu.id)">刷新列表</el-button>
        <el-button type="primary" @click="handleAddProductSkuButtonClick(prodCurrentSpu)">添加规格产品</el-button>
        <el-button type="danger" @click="handleDeleteSkuListButtonClick(prodCurrentSpu.id)">批量删除</el-button>

      </el-row>
      <el-row>
        <el-table
          :key="Math.random()"
          :class="['table-border']"
          :data="prodCurrentSpu.skus"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChangeInSkuTable"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column
            prop="code"
            label="sku编码"
            width="150"
          >
          </el-table-column>
          <el-table-column
            label="sku名称"
            :autosize="true"
          >
            <template slot-scope="scope">
              <el-input type="textarea" v-model="scope.row.name"
                @change="handleSetNameOfSku(scope.row)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="价格(分)"
            width="130"
          >
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.price"
                        @change="handleSetPriceOfSku(scope.row)">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="库存(件)"
            width="130"
          >
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.count"
                        @change="handleSetCountOfSku(scope.row)">
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button type="primary" @click="handleOpenSkuDetailsButtonClick(scope.row.id)">货品详情</el-button>
              <el-button type="warning" @click="handleEditParametersOfSkuButtonClick(scope.row.id)">参数编辑</el-button>
              <el-button type="warning" @click="handleEditImagesOfSkuButtonClick(scope.row.id)">图片编辑</el-button>
              <el-button type="danger" @click="handleDeleteOneSkuButtonClick(scope.row.id,prodCurrentSpu.id)">删除
              </el-button>
            </template>

          </el-table-column>
        </el-table>
      </el-row>
    </el-card>


    <el-dialog
      title="货品详情"
      :visible.sync="isSkuDetailsDialogVisible"
      width="58%">
      <el-collapse v-if="isSkuDetailsDialogVisible" v-model="skuDetailActiveName">
        <el-collapse-item title="基本信息" name="1">
          <el-row :class="['contentArea']">
            <el-col :span="12">
              <h2>货品编号:</h2>
              <h3>{{prodCurrentSku.code}}</h3>
            </el-col>
            <el-col :span="12">
              <h2>货品名称:</h2>
              <h3>{{prodCurrentSku.name}}</h3>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item v-if="prodCurrentSku.images.length>0" title="货品图片" name="2">
          <el-row :class="['contentArea']">
            <el-row>
              <el-image
                v-for="image in prodCurrentSku.images" :key="''+image.id"
                style="width: 450px; height: 450px"
                :src="imageServer+'/'+image.largeImage"
                fit="fit"
              ></el-image>
            </el-row>
          </el-row>
        </el-collapse-item>
        <el-collapse-item v-if="prodCurrentSku.attrs.length>0" title="货品属性" name="3">
          <el-row :class="['contentArea']">
            <el-row>
              <el-col :span="12" v-for="attr in prodCurrentSku.attrs" :key="''+attr.attrId">
                <h2>{{attr.attrName}}:</h2>
                <h3>{{attr.attrOptionValue}}</h3>
              </el-col>
            </el-row>
          </el-row>
        </el-collapse-item>
        <el-collapse-item v-if="prodCurrentSku.specs.length>0" title="货品规格" name="4">
          <el-row :class="['contentArea']">
            <el-row>
              <el-col :span="12" v-for="spec in prodCurrentSku.specs" :key="''+spec.specId">
                <h2>{{spec.specName}}:</h2>
                <h3>{{spec.specOptionValue}}</h3>
              </el-col>
            </el-row>
          </el-row>
        </el-collapse-item>

      </el-collapse>

    </el-dialog>

  </div>
</template>

<script>

  import {mapState, mapMutations} from 'vuex';
  import {prodTabNameList} from "../../config/variable";
  import ImageListEdit from '../comp/ImageListEdit'
  export default {
    name: "ProdDetails",
    components: {ImageListEdit},
    data() {
      return {
        currentModifyingSKU: {},
        selectionInSkuTable: [],
        isSkuDetailsDialogVisible: false,
        skuDetailActiveName:[]
      }
    },



    computed: {


      ...mapState({
        ossServer:state=>state.prod.ossServer,
        imageServer:state=>state.prod.imageServer,
        prodActiveTabName:state=>state.prod.prodActiveTabName,
        prodCurrentSpu:state=>state.prod.prodCurrentSpu,
        prodNewSkuFormData: state=>state.prod.prodNewSkuFormData,
        prodCurrentSku:state=>state.prod.prodCurrentSku
      }),


      prodCurrentSpuImages: {
        get: function () {
          return this.$store.state.prod.prodCurrentSpuImages;
        },
        set: function (val) {
          this.$store.commit('setProdCurrentSpuImages', val);
        }
      }
    },

    mounted(){
      this.refreshSkuListFunction(this.prodCurrentSpu.id);
    },

    methods: {
      ...mapMutations(['setProdActiveTabName', 'setProdNewSkuFormData',
        'setProdCurrentSku', 'setProdCurrentModifyingSku','setProdActiveTabName']),

      // 修改名称
      async handleSetNameOfSku(row){
        const result = await this.$confirm("确认要修改货品名称?","提示").catch(error=>null);
        if(result==='confirm') {
          this.api.__api__ProductSkuNameUpdate(row.id, row.name)
            .then(data => {
              this.refreshSkuListFunction(this.prodCurrentSpu.id);
            }).catch(error => console.error(error))
        }else {
          this.refreshSkuListFunction(this.prodCurrentSpu.id);
        }
      },

      // 修改库存
      async handleSetCountOfSku(row){
        const result = await this.$confirm("确认要修改库存?","提示").catch(error=>null);
        if(result==='confirm') {
          this.api.__api__ProductSkuCountUpdate(row.id, row.count)
            .then(data => {
              this.refreshSkuListFunction(this.prodCurrentSpu.id);
            }).catch(error => console.error(error))
        }else {
          this.refreshSkuListFunction(this.prodCurrentSpu.id);
        }
      },

      // 修改价格
      async handleSetPriceOfSku(row){
        console.log("row="+JSON.stringify(row));
        const result = await this.$confirm("确认要修改价格?","提示").catch(error=>null);
        if(result==='confirm') {
          this.api.__api__ProductSkuPriceUpdate(row.id, row.price)
            .then(data => {
              this.refreshSkuListFunction(this.prodCurrentSpu.id);
            }).catch(error => console.error(error))
        }else {
          this.refreshSkuListFunction(this.prodCurrentSpu.id);
        }
      },

      //处理SPU的图片添加
      handleImageListEditUploadSuccess(response, file, fileList) {
        var imageObject = new Object();
        imageObject.image = response.data[0];
        imageObject.spuId = this.prodCurrentSpu.id;
        this.api.__api__ProductSpuImageAdd(imageObject)
          .then(data => {
            this.api.__api__ProductSpuImages(this.prodCurrentSpu.id)
              .then(data1 => {
                this.prodCurrentSpuImages = data1.data;
                this.$message.success("保存图片成功");
              }).catch(error => console.log(error));
          }).catch(error => {
          this.api.__api__OSS_DeleteFile(this.ossServer, imageObject.image)
            .then(data => {
              console.log(data.message)
            })
            .catch(error => console.error(error));

        })
      },

      //处理SPU的图片删除
      async handleRemoveImage(image) {
        console.log("call handleRemoveImage...,image=" + JSON.stringify(image));
        const result = await this.$confirm("确定要删除这张图片?", "提示").catch(error => null);
        if (result === 'confirm') {
          //用于学习目的先不要真实删除图片
          // this.api.__api__OSS_DeleteFile(this.ossServer, image.image)
          //   .then(data => {
              this.api.__api__ProductSpuImageDelete(image.id)
                .then(data2 => {

                  this.api.__api__ProductSpuImages(this.prodCurrentSpu.id)
                    .then(data3 => {
                      this.prodCurrentSpuImages = data3.data;

                    }).catch(error => console.error(error));
                  this.$message.success(data.message);
                })
                .catch(error => {
                  this.$message.error(error)
                });

            // })
            // .catch(error => null);
        }
      },

      //添加SKU
      handleAddProductSkuButtonClick(spu) {
        var newSkuFormData = {};

        newSkuFormData.name = '';
        newSkuFormData.code = '';//  code:'',
        newSkuFormData.price = 0; //  price: 0,
        newSkuFormData.count = 0; //count: 0,
        newSkuFormData.spuId = spu.id;
        var p1 = this.api.__api__CategoriesAttrs(this.prodCurrentSpu.cate3Id);
        var p2 = this.api.__api__CategoriesSpecs(this.prodCurrentSpu.cate3Id);
        Promise.all([p1, p2]).then(values => {
          newSkuFormData.attrs = values[0].data;
          newSkuFormData.specs = values[1].data;
          this.setProdNewSkuFormData(newSkuFormData);
          this.setProdActiveTabName(prodTabNameList.prodSkuAdd);
        })
          .catch(errors => null);

      },

      //记录sku表中选中的项
      handleSelectionChangeInSkuTable(selection) {
        this.selectionInSkuTable = selection;
      },

      // 刷新SKU列表按钮回调
      handleRefreshSkuListButtonClick(spuId) {
        this.refreshSkuListFunction(spuId);
      },

      // 刷新SKU列表
      refreshSkuListFunction(spuId){
        this.api.__api__ProductSpuSkus(spuId)
          .then(data => {
            this.$store.state.prod.prodCurrentSpu = Object.assign({},this.$store.state.prod.prodCurrentSpu,{skus:data.data})
          })
          .catch(error =>{
            this.$store.state.prod.prodCurrentSpu.skus = [];
          });
      },

      //处理批量删除SKU
      async handleDeleteSkuListButtonClick(spuId) {
        if (this.selectionInSkuTable.length == 0) {
          this.$message.info("请选中一个或多个规格产品");
          return;
        }
        const result = await this.$confirm("您确定要删除选中的规格产品?", '提示').catch(error => null);
        if (result === 'confirm') {
          const skuIdList = [];
          for (let sku of this.selectionInSkuTable) {
            skuIdList.push(sku.id);
          }

          this.api.__api__ProductSkusDelete(skuIdList)
            .then(data => {
              this.$message.success(data.message);
              this.refreshSkuListFunction(spuId);
            })
            .catch(error => console.error(error))
        }
      },

      // 打开SKU详情
      handleOpenSkuDetailsButtonClick(skuId) {
        this.api.__api__ProductSkuDetails(skuId)
          .then(data => {
            this.setProdCurrentSku(data.data);
            console.log("data.data=" + JSON.stringify(data.data));
            this.isSkuDetailsDialogVisible = true;
          }).catch(error => console.error(error));


      },

      //处理删除一条SKU
      async handleDeleteOneSkuButtonClick(skuId, spuId) {
        const result = await this.$confirm("您确定要删除该条规格产品?", '提示').catch(error => null);
        if (result === 'confirm') {
          this.api.__api__ProductSkuDelete(skuId)
            .then(data => {
              this.$message.success(data.message);
              this.refreshSkuListFunction(spuId);
            })
            .catch(error => console.error(error))
        }
      },

      //打开货品参数编辑页
      handleEditParametersOfSkuButtonClick(skuId){
        this.api.__api__ProductSkuDetails(skuId)
          .then(data=>{
            this.setProdCurrentModifyingSku(data.data);
            this.setProdActiveTabName(prodTabNameList.prodSkuModify)
          }).catch(error=>console.error(error));
      },

      //打开图片编辑面
      handleEditImagesOfSkuButtonClick(skuId){

      }

    }
  }
</script>

<style scoped>
  .placeholder {
    display: flex;
    justify-content: center;
    align-content: center;
    align-items: center;
  }

  h2 + h3 {
    border: 1px solid #c0ccda;
    margin-right: 50px;
    padding: 6px;
    padding-left: 12px;
    border-radius: 3px;
  }

  .dialogTitle {
    font-size: 30px;
  }

  .detailArea{
    border:1px solid #c0ccda;
    padding:20px;
    border-radius: 5px;
  }

  .contentArea{
    background-color: #e1f3d8;
    padding:10px;
    border-radius: 5px;
  }

  .el-image{
    margin:10px;
  }

</style>
